<?php

class AdminManage
{
    var $pdo = null;
    var $logger = null;
    function __construct()
    {
        $this->pdo = PDOWrapper::instance();
        $this->logger = CLog::getInstance();
    }

    /**
    * 插入数据库新功能，分配新部门功能
    */
    function UpdateV1($GetParams, $PostArray){

        $class_name = ['AdminSearch','AdminAdd','AdminModify','AdminDelete'];
        $num = 1;
        $function = [];
        foreach ($class_name as $k => $v) {
            $method = get_class_methods($v);
            foreach ($method as $key => $value) {
                if($key == 0){
                    continue;
                }
                $pull = [
                    strtolower(substr($v, 5)).'_'.$value => $num
                ];
                $num++;
                $function = array_merge($function,$pull);
            }
        }

        // if(!isset($PostArray['token'])) {
        //     Utils::ShowError(ErrorDefine::SHORT_OF_TOKEN);
        //     return false;
        // }
        // $token = $PostArray['token'];
        // $admin = User::GetAidByToken($token);

        // if($admin === false) {
        //     Utils::ShowError(ErrorDefine::INVALID_TOKEN);
        //     return false;
        // }
        // $admin_id = $admin['admin_id'];
        // if($admin['admin_type'] != 1000){
        //     Utils::ShowError('404','权限不够');
        //     return false;
        // }

        $field = ['dept_id'];
        $order_by = ['dept_id' => 'DESC'];
        $dept = $this->pdo->select('department',$field,null,1,null,$order_by);
        $dept = $dept['dept_id'];
        
        $field = ['auth_id'];
        $order_by = ['auth_id' => 'DESC'];
        $auth_id = $this->pdo->select('auth',$field,null,1,null,$order_by);
        $auth_id = $auth_id['auth_id'];

        if($dept>$auth_id && !empty($auth_id)){
            foreach ($function as $key => $value) {
                $auth_id = $dept + $value;
                $params = [
                    'auth_id' => $auth_id,
                    'auth' => 0
                ];
                $auth = $this->pdo->insert('auth',$params);
            }
        }

        $newfunction = self::UpdateFunction($function);
        if($newfunction === false){
            return false;
        }

        Utils::ShowMessage();
        return true;
    }

    /**
     * @return array|bool
     * 
     * 管理员修改功能接口
     */
    function ModifyV1($GetParams, $PostArray){

        if(!isset($PostArray['modify_type'])){
            Utils::ShowError(400,'修改类型为空');
            return false;
        }

        $admin_id = self::CheckParams($PostArray);
        if(false === $admin_id) {
            return false;
        }

        $modify = new AdminModify();
        $method = get_class_methods($modify);
        $function = self::CheckMethod($method,$PostArray['modify_type']);
        if($function === false){
            return false;
        }

        $descri = $modify->$function($PostArray); 

        if($descri === false) {
            return false;
        }  

        if(empty($descri)) {
            Utils::ShowError(4000,'没有任何修改！');
            return false;
        }   

        $res = self::RecordDescri($PostArray,$admin_id);
        if(empty($res)){
            return false;
        }

        Utils::ShowMessage();
        return true;
    }

    /**
     * @return array|bool
     * 
     * 管理员添加功能接口
     */
    function AddV1($GetParams, $PostArray){

        if(!isset($PostArray['add_type'])){
            Utils::ShowError(401,'添加类型为空');
            return false;
        }

        $admin_id = self::CheckParams($PostArray);
        if(false === $admin_id) {
            return false;
        }

        $add = new AdminAdd();
        $method = get_class_methods($add);
        $function = self::CheckMethod($method,$PostArray['add_type']);
        if($function === false){
            return false;
        }

        $descri = $add->$function($PostArray);

        if($descri === false) {
            return false;
        }  

        if(empty($descri)) {
            return false;
        }   

        $res = self::RecordDescri($PostArray,$admin_id);
        if(empty($res)){
            return false;
        }

        Utils::ShowMessage();
        return true;
    }

    /**
     * @return array|bool
     * 
     * 管理员查看接口
     */
    function SearchV1($GetParams, $PostArray){

        if(!isset($PostArray['search_type'])){
            Utils::ShowError(402,'查询类型为空');
            return false;
        }

        $admin_id = self::CheckParams($PostArray);
        if(false === $admin_id) {
            return false;
        }

        $search = new AdminSearch();
        $method = get_class_methods($search);
        $function = self::CheckMethod($method,$PostArray['search_type']);
        if($function === false){
            return false;
        }

        $descri = $search->$function($PostArray);

        if($descri === false) {
            return false;
        }  

        if(empty($descri)) {
            return false;
        }   

        $res = self::RecordDescri($PostArray,$admin_id);
        if(empty($res)){
            return false;
        }

        Utils::ShowMessage($descri);
        return true;
    }

    /**
     * @return array|bool
     * 
     * 管理员删除功能接口
     */
    function DeleteV1($GetParams, $PostArray){

        if(!isset($PostArray['delete_type'])){
            Utils::ShowError(403,'删除类型为空');
            return false;
        }

        $admin_id = self::CheckParams($PostArray);
        if(false === $admin_id) {
            return false;
        }

        $delete = new AdminDelete();
        $method = get_class_methods($delete);
        $function = self::CheckMethod($method,$PostArray['delete_type']);
        if($function === false){
            return false;
        }

        $descri = $delete->$function($PostArray);
        
        if($descri === false) {
            return false;
        }  

        if(empty($descri)) {
            return false;
        }   

        $res = self::RecordDescri($PostArray,$admin_id);
        if(empty($res)){
            return false;
        }

        Utils::ShowMessage();
        return true;
    }

    

    private function UpdateFunction($function){

        $newfunction = [];
        $field = ['func_name'];
        $funcs_name = $this->pdo->select('function',$field);
        $num = 1;
        $origin_func = [];
        foreach ($funcs_name as $key => $value) {

            $pull = [
                $value['func_name'] => $num
            ];
            $num++;
            $origin_func = array_merge($origin_func,$pull);
        }

        $newfunction = array_diff_key($function, $origin_func);

        if(empty($newfunction)){
            Utils::ShowError('405','无需更新');
            return false;
        }
        
        foreach ($newfunction as $key => $value) {
            $param = [
                'func_name' => $key
            ];
            $func_ret = $this->pdo->insert('function',$param);
            if(empty($func_ret)){
                Utils::ShowError(ErrorDefine::SYSTEM_ERROR);
                return false;
            }

        }

        $field = ['dept_id'];
        $dept = $this->pdo->select('department',$field);

        foreach ($dept as $key => $value) {
            foreach ($newfunction as $k => $v) {
                $auth_id = $value['dept_id'] + $v;
                switch ($value['dept_id']) {
                    case 1000:
                        $auth = 1;
                        break;
                    
                    default:
                        $auth = 0;
                        break;
                }
            
                $params = [
                    'auth_id' => $auth_id,
                    'auth' => $auth
                ];
                $auth_ret = $this->pdo->insert('auth',$params);
            }
        }

        return $newfunction;
    }

    /**
    * 检查管理员是否登录以及管理员访问权限
    */
    private function CheckParams($PostArray){
        
        if(!isset($PostArray['token'])) {
            Utils::ShowError(ErrorDefine::SHORT_OF_TOKEN);
            return false;
        }
        $token = $PostArray['token'];
        $admin = User::GetAidByToken($token);
        
        if($admin === false) {
            Utils::ShowError(ErrorDefine::INVALID_TOKEN);
            return false;
        }
        $admin_id = $admin['admin_id'];
        $beh_type = self::CheckBType($PostArray);

        $auth = self::Auth($admin['admin_type'],$beh_type);
        if($auth === false){
            return false;
        }
        
        return $admin_id;
    }

    private function CheckBType($PostArray){

        if(isset($PostArray['search_type'])) {
            $type = 'search_type';
            $content = $PostArray['search_type'];
        } 
        elseif (isset($PostArray['add_type'])) {
            $type = 'add_type';
            $content = $PostArray['add_type'];
        } 
        elseif (isset($PostArray['modify_type'])) {
            $type = 'modify_type';
            $content = $PostArray['modify_type'];
        } 
        elseif (isset($PostArray['delete_type'])) {
            $type = 'delete_type';
            $content = $PostArray['delete_type'];
        }

        $fields = explode("_", $type);
        $beh_type = $fields[0];
        $beh_type = $beh_type.'_'.$content;

        return $beh_type;
    }

    /**
    * 管理员操作成功后生产管理员行为日志
    */
    private function RecordDescri($PostArray,$admin_id){

        $descri = '';
        $add_comma = false;
        foreach ($PostArray as $column => $content) {

            if($column == 'token'){
                continue;
            } 
            elseif ($column == 'modify_type') {
                continue;
            }
            elseif ($column == 'add_type') {
                continue;
            } 
            elseif ($column == 'search_type') {
                continue;
            }
            elseif ($column == 'delete_type') {
                continue;
            }

            if ($add_comma) {
                $descri .= ', ';
            }
            else {
                $add_comma = true;
            }

            if( is_array($content) && count($content) > 0 ){
                
                $descri.= $column.' : ';
                $add_comma = false;

                foreach ($content as $k => $v) {
                    if ($add_comma) {
                        $descri .= ', ';
                    }
                    else {
                        $add_comma = true;
                    }
                    $descri .= "$v";
                }
                continue;
            }
            
            $descri .= "$column : $content";
            
        }
        $beh_type = self::CheckBType($PostArray);

        $param = array(
            'admin_id' => $admin_id,
            'log_type' => $beh_type,
            'remark' => $descri
        );

        $res = $this->pdo->insert('admin_log',$param);
        if(empty($res)){
            Utils::ShowError(ErrorDefine::UPDATE_TABLE_FAILED);
            return false;
        }

        return $res;
    }

    private function CheckMethod($method,$type){

        if(in_array($type,$method) === true){
            return $type;
        } else {
            Utils::ShowError(ErrorDefine::INVALID_BUSINESS_TYPE);
            return false;
        }
    }

    /**
    * @param $admin_type 管理员类型
    * @param $beh_type 管理员动作 接口+type
    * @return true 有权限
    * @return false 没有权限
    */
    private function Auth($admin_type,$beh_type){

        if($admin_type == 1000){
            return true;
        }
        $param = [
            'func_name' => $beh_type
        ]; 
        $field = ['func_id'];
        $func_id = $this->pdo->select('function',$field,$param);
        if(empty($func_id)){
            Utils::ShowError(ErrorDefine::INVALID_BUSINESS_TYPE);
            return false;
        }
        $func_id = $func_id[0]['func_id'];

        $auth_id = $admin_type + $func_id;
        $param = [
            'auth_id' => $auth_id
        ];
        $field = ['auth'];
        $auth = $this->pdo->select('auth',$field,$param);

        if($auth[0]['auth'] == 0){
            Utils::ShowError('404','权限不够');
            return false;
        }

        return true;
    }


    function AutoCreateV1($GetParams, $PostArray){

        $res = $this->pdo->query("SHOW TABLE STATUS");
        foreach ($res as $key => $value) {
        
            //自动构建查询
            $search_txt = '
    //'.$value["Comment"].'
    function '.$value["Name"].'($PostArray) {
        $page_no = 0;
        if(isset($PostArray[\'page_no\'])){
            $page_no = $PostArray[\'page_no\'];
        }
        $page_size = 10;
        if(isset($PostArray[\'page_size\'])){
            $page_size = $PostArray[\'page_size\'];
        }
        $sql="SELECT * FROM '.$value["Name"].' ";

        if(isset($PostArray[\'record_user_id\'])){
            $record_user_id = $PostArray[\'record_user_id\'];
            $sql= $sql." WHERE record_user_id={$record_user_id}";
        }

        $sql=  $sql." LIMIT {$start},{$page_size}";
        $'.$value["Name"].'_res = $this->pdo->query($sql);

        $sql="SELECT count(record_id) AS num  FROM '.$value["Name"].' ";
        $count = $this->pdo->query($sql);

        $data = array(
            \'num\'=>$count[0][\'num\'],
            \''.$value["Name"].'\'=>$'.$value["Name"].'_res
        );

        return $data;
    }'."\n";
            $searchfile = 'api/AdminSearch.class.php';
            file_put_contents($searchfile,$search_txt,FILE_APPEND);


            $table = $this->pdo->query("SHOW FULL COLUMNS FROM ".$value["Name"]."");

            $field_fill = '';
            $primary_key = '';
            $fill_params = '
        $params = array(';

            foreach ($table as $k => $v) {
                if($v['Key'] === 'PRI'){
                    $primary_key = '
        if(empty($PostArray[\''.$v["Field"].'\'])){
            Utils::ShowError(ErrorDefine::REQUIRED_FIELD_EMPTY);
            return false;
        }'."\n";
                    $key_params = '
        $where = array(
            \''.$v["Field"].'\' => $PostArray[\''.$v["Field"].'\']
        );';
                    continue;
                }

                if($v['Null'] === 'NO'){
                    $field_fill .= '
        if(empty($PostArray[\''.$v["Field"].'\'])){
            Utils::ShowError(ErrorDefine::REQUIRED_FIELD_EMPTY);
            return false;
        }';
                }else{
                    $field_fill .= '
        if(!isset($PostArray[\''.$v["Field"].'\'])){
            Utils::ShowError(ErrorDefine::REQUIRED_FIELD_EMPTY);
            return false;
        }';
                }
                $fill_params .='
            \''.$v["Field"].'\' => $PostArray[\''.$v["Field"].'\'],'."\n";
                
            }
            $fill_params .= '
        );';

            //自动构建删除功能
            $delete_txt = '
    //'.$value["Comment"].'
    function '.$value["Name"].'($PostArray) {
'.$primary_key.'
'.$key_params.'
        $ret = $this->pdo->select(\''.$value["Name"].'\',null,$where);
        if(empty($ret)){
            Utils::ShowError(ErrorDefine::DATABASE_ERROR);
            return false;
        }
        
        $data = $this->pdo->delete(\''.$value["Name"].'\',$where);

        return $data;
    }'."\n";
            $deletefile = 'api/AdminDelete.class.php';
            file_put_contents($deletefile,$delete_txt,FILE_APPEND);

            //自动构建添加功能
            $add_txt = '
    //'.$value["Comment"].'
    function '.$value["Name"].'($PostArray) {

'.$field_fill.'

'.$fill_params.'
        $data = $this->pdo->insert(\''.$value["Name"].'\',$params);

        return $data;
    }'."\n";
            $addfile = 'api/AdminAdd.class.php';
            file_put_contents($addfile,$add_txt,FILE_APPEND);

            //自动构建修改功能
            $modify_txt = '
    //'.$value["Comment"].'
    function '.$value["Name"].'($PostArray){

'.$primary_key.'
'.$field_fill.'

'.$key_params.'

'.$fill_params.'
        $ret = $this->pdo->select(\''.$value["Name"].'\',null,$where);
        if(empty($ret)){
            Utils::ShowError(ErrorDefine::DATABASE_ERROR);
            return false;
        }
        
        $data = $this->pdo->update(\''.$value["Name"].'\',$param,$where);

        return $data;
    }'."\n";

            $modifyfile = 'api/AdminModify.class.php';
            file_put_contents($modifyfile,$modify_txt,FILE_APPEND);
        }
        $end = '
}';
        $modifyfile = 'api/AdminModify.class.php';
        file_put_contents($modifyfile,$end,FILE_APPEND);

        $addfile = 'api/AdminAdd.class.php';
        file_put_contents($addfile,$end,FILE_APPEND);

        $deletefile = 'api/AdminDelete.class.php';
        file_put_contents($deletefile,$end,FILE_APPEND);

        $searchfile = 'api/AdminSearch.class.php';
        file_put_contents($searchfile,$end,FILE_APPEND);
                    

    }


}


?>